package com.rockcent.wechat.helper;

import com.alibaba.fastjson.JSON;
import com.rockcent.common.utils.DateFormatUtils;
import com.rockcent.common.utils.DateUtils;
import com.rockcent.common.utils.HttpClientUtils;
import com.rockcent.mall.lib.domain.MallOrder;
import com.rockcent.mall.lib.domain.MallWechatConfig;
import com.rockcent.mall.lib.domain.MiniAppConfig;
import com.rockcent.mall.lib.repository.WechatConfigRepository;
import com.rockcent.message.bean.TemplateData;
import com.rockcent.message.bean.WxAppTemplate;
import com.rockcent.message.bean.WxTemplate;
import com.rockcent.message.util.WeixinTemplateUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestHeader;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.MessageFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Component
public class WxAppMsgTemplateHelper {
    @Autowired
    private WechatConfigRepository wechatConfigRepository;

    private final Logger log = LoggerFactory.getLogger(WxAppMsgTemplateHelper.class);

    public void sendWxMsg(String domain, String wxOpenId, String customerName, MallOrder mallOrder) throws IOException {
        BigDecimal totalFee = mallOrder.getActualAmount();
        String mallOrderNum = mallOrder.getOrderNum();
        WxTemplate template = new WxTemplate();

        String url = domain + "/wechat/mine";
        template.setTopcolor("#000000");
//        template.setTemplate_id("LZg4DOUV68Bqz_8Hyy9x_F5ow2ZciJxC4Jbydn0PEAI");
        template.setTemplate_id("9RKCvari4yneYQERzmBIh5u6-ZR_5UqzXJN-re21Ybk");
        template.setTouser(wxOpenId);
        template.setUrl(url);
        Map<String, TemplateData> dataHashMap = new HashMap<String, TemplateData>();
        TemplateData first = new TemplateData();
        first.setValue("尊敬的" + customerName + "，您好，你的订单已支付成功，订单号：" + mallOrderNum);
        first.setColor("#173177");
        dataHashMap.put("first", first);

        TemplateData orderMoneySum = new TemplateData();
        orderMoneySum.setValue(totalFee.setScale(2, BigDecimal.ROUND_HALF_UP).toString());
        orderMoneySum.setColor("#173177");
        dataHashMap.put("orderMoneySum", orderMoneySum);

        TemplateData orderProductName = new TemplateData();
        String productName = mallOrder.getGiftName();
        if (StringUtils.isBlank(productName)) {
            productName = "普通商品";
        }
        orderProductName.setValue(productName);
        orderProductName.setColor("#173177");
        dataHashMap.put("orderProductName", orderProductName);


        TemplateData Remark = new TemplateData();
        Remark.setValue(mallOrder.getRemark());
        Remark.setColor("#173177");
        dataHashMap.put("Remark", Remark);
        template.setData(dataHashMap);


        log.info("====================>template:{}", template);


        MallWechatConfig config = wechatConfigRepository.queryWechatConfigByDomain(domain);
        String access_token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}";
        access_token_url = MessageFormat.format(access_token_url, config.getAppid(), config.getAppSecret());
        String result = HttpClientUtils.SINGLETON.sendGet(access_token_url);
        Map mapTypes = JSON.parseObject(result);
        String access_token = (String) mapTypes.get("access_token");
        log.info("====================>access_token:{}", access_token);
        log.info("====================>result:{}", result);
        log.info("====================>config:{}", config);
        WeixinTemplateUtil.sendMessage(template, access_token, WeixinTemplateUtil.weiXinSenurl);


    }

    /**
     * @param domain        域名
     * @param wxOpenId      小程序个人openId
     * @param customerName  用户名
     * @param mallOrder     订单
     * @param prePayId      支付Id
     * @param miniAppConfig MiniAppConfig
     * @throws IOException
     */
    public void sendWxAppMsg(String domain, String wxOpenId, String customerName, MallOrder mallOrder, String prePayId, MiniAppConfig miniAppConfig) throws IOException {

        log.info("====================>config:{}", miniAppConfig);


        String tempateId = miniAppConfig.getTemplateId();
        BigDecimal totalFee = mallOrder.getActualAmount();
        String mallOrderNum = mallOrder.getOrderNum();
        WxAppTemplate template = new WxAppTemplate();

        String url = /*domain +*/ "/pages/mine/mine";
        template.setColor("#000000");
        template.setTemplate_id(tempateId);
        template.setTouser(wxOpenId);
        template.setPage(url);
        template.setForm_id(prePayId);
        Map<String, TemplateData> dataHashMap = new HashMap<String, TemplateData>();
        TemplateData first = new TemplateData();
        Date orderDate = mallOrder.getLastUpdated();
        String orderDateStr = DateUtils.date2String(orderDate, "yyyy-MM-dd HH:mm:ss");
        first.setValue(orderDateStr);
        first.setColor("#173177");
        dataHashMap.put("keyword1", first);


        TemplateData orderProductName = new TemplateData();
        String productName = mallOrder.getGiftName();
        if (StringUtils.isBlank(productName)) {
            productName = "普通商品";
        }
        orderProductName.setValue(productName);
        orderProductName.setColor("#173177");
        dataHashMap.put("keyword2", orderProductName);


        TemplateData Remark = new TemplateData();
        Remark.setValue(mallOrderNum);
        Remark.setColor("#173177");
        dataHashMap.put("keyword3", Remark);
        template.setData(dataHashMap);

        TemplateData orderMoneySum = new TemplateData();
        orderMoneySum.setValue(totalFee.setScale(2, BigDecimal.ROUND_HALF_UP).toString());
        orderMoneySum.setColor("#173177");
        dataHashMap.put("keyword4", orderMoneySum);


        log.info("====================>template:{}", template);


//        MallWechatConfig config = wechatConfigRepository.queryWechatConfigByDomain(domain);
        String access_token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}";
        access_token_url = MessageFormat.format(access_token_url, miniAppConfig.getAppId(), miniAppConfig.getAppSecret());
        String result = HttpClientUtils.SINGLETON.sendGet(access_token_url);
        Map mapTypes = JSON.parseObject(result);

        String access_token = (String) mapTypes.get("access_token");
        log.info("====================>access_token:{}", access_token);
        log.info("====================>result:{}", result);
        WeixinTemplateUtil.sendMessage(template, access_token, WeixinTemplateUtil.weiAppSenurl);


    }
}
